package com.soft.face.config.security;

import cn.hutool.json.JSONUtil;
import com.soft.face.global.Constant;
import com.soft.face.global.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Slf4j
public class SecurityFilter implements Filter {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    // 请求黑名单
    private final List<String> blackList = Stream.of(
            "/face/**",
            "/file/**",
            "/arcsoft/**"
    ).collect(Collectors.toList());

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 简单的模拟接口访问校验操作
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String uri = httpServletRequest.getRequestURI();
        if (requestCheck(uri)) {
            // 校验是否有token
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            String token = httpServletRequest.getHeader(Constant.TOKEN);
            if (StringUtils.isEmpty(token)) {
                response.getWriter().print(JSONUtil.parse(R.failed("token不能为空")));
                return;
            }
            // 校验token是否存在
            if (!TokenStage.check(token)) {
                response.getWriter().print(JSONUtil.parse(R.failed(403, "登录失效请重新登录")));
                return;
            }

        }
        filterChain.doFilter(request, response);
    }

    /**
     * 请求校验 true为匹配 false为失败
     *
     * @param uri
     * @return
     */
    public boolean requestCheck(String uri) {
        for (String u : blackList) {
            if (pathMatcher.match(u, uri)) {
                return true;
            }
        }
        return false;
    }

}
